<?php

/**
 * This is the model class for table "tbl_product_picture".
 *
 * The followings are the available columns in table 'tbl_product_picture':
 * @property integer $id
 * @property string $name
 * @property string $path
 * @property integer $product_id
 */
class ProductPicture extends CActiveRecord
{
	public $uploadedFile;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return ProductPicture the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_product_picture';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, path, product_id', 'required'),
			array('product_id', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>64),
			array('path', 'length', 'max'=>255),
			
			// Rule for upload file
			array('uploadedFile','file','types'=>'jpg,jpeg,gif,png'),
			
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, path, product_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'product'=>array(self::BELONGS_TO,'Product','product_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Name',
			'path' => 'Path',
			'product_id' => 'Product',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('path',$this->path,true);
		$criteria->compare('product_id',$this->product_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function afterSave( ) {
		$this->addImages( );
		parent::afterSave( );
	}
	
	public function addImages( ) {
		//If we have pending images
		if( Yii::app( )->user->hasState( 'images' ) ) {
			$userImages = Yii::app( )->user->getState( 'images' );
			//Resolve the final path for our images
			$path = Yii::app( )->getBasePath( )."/../images/uploads/{$this->id}/";
			//Create the folder and give permissions if it doesnt exists
			if( !is_dir( $path ) ) {
				mkdir( $path );
				chmod( $path, 0777 );
			}
	
			//Now lets create the corresponding models and move the files
			foreach( $userImages as $image ) {
				if( is_file( $image["path"] ) ) {
					if( rename( $image["path"], $path.$image["filename"] ) ) {
						chmod( $path.$image["filename"], 0777 );
						$img = new Image( );
						$img->size = $image["size"];
						$img->mime = $image["mime"];
						$img->name = $image["name"];
						$img->source = "/images/uploads/{$this->id}/".$image["filename"];
						$img->somemodel_id = $this->id;
						if( !$img->save( ) ) {
							//Its always good to log something
							Yii::log( "Could not save Image:\n".CVarDumper::dumpAsString(
									$img->getErrors( ) ), CLogger::LEVEL_ERROR );
							//this exception will rollback the transaction
							throw new Exception( 'Could not save Image');
						}
					}
				} else {
					//You can also throw an execption here to rollback the transaction
					Yii::log( $image["path"]." is not a file", CLogger::LEVEL_WARNING );
				}
			}
			//Clear the user's session
			Yii::app( )->user->setState( 'images', null );
		}
	}
}